package com.niiwoo.civet.mobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.niiwoo.asset.org.business.dto.response.OrgApplyCreditCardInfoRespDTO;
import com.niiwoo.asset.org.business.dto.response.OrgApplySocialSecurityInfoRespDTO;
import com.niiwoo.asset.org.business.service.dubbo.OrgProjectOrderDubboService;
import com.niiwoo.civet.mobile.vo.common.LinkManInfoVO;
import com.niiwoo.civet.mobile.vo.common.RelatedFileVO;
import com.niiwoo.civet.mobile.vo.request.user.LoanUserDataInfoRequestVO;
import com.niiwoo.civet.mobile.vo.request.user.UserPortraitRequsetVo;
import com.niiwoo.civet.mobile.vo.response.CreditCardInfoResponseVO;
import com.niiwoo.civet.mobile.vo.response.user.*;
import com.niiwoo.civet.snapdata.dto.response.*;
import com.niiwoo.civet.snapdata.enums.SocialSecurityFeeStatus;
import com.niiwoo.civet.snapdata.service.TianChengDataAnalysisDubboService;
import com.niiwoo.civet.snapdata.service.UserDataSnapshotDubboService;
import com.niiwoo.civet.snapdata.service.YXCreditCardDubboService;
import com.niiwoo.civet.trade.dto.common.ProjectDTO;
import com.niiwoo.civet.trade.dto.response.SpeedLoanRecordStatisticsDTO;
import com.niiwoo.civet.trade.dto.response.org.AssetOrgProjectResponseDTO;
import com.niiwoo.civet.trade.dto.response.orgloan.OrgApplyHouseResponseDTO;
import com.niiwoo.civet.trade.dto.response.orgloan.OrgApplyLoanInfoResponseDTO;
import com.niiwoo.civet.trade.dto.response.orgloan.OrgApplyPersonResponseDTO;
import com.niiwoo.civet.trade.dto.response.orgloan.OrgApplyWorkResponseDTO;
import com.niiwoo.civet.trade.enums.LoanTypeEnum;
import com.niiwoo.civet.trade.enums.ProjectTypeEnum;
import com.niiwoo.civet.trade.service.ProjectCommonDubboService;
import com.niiwoo.civet.trade.service.configure.TradeConfigDubboService;
import com.niiwoo.civet.trade.service.org.OrgProjectDubboService;
import com.niiwoo.civet.trade.service.project.ProjectDubboService;
import com.niiwoo.civet.user.dto.LinkManDubboInfoDTO;
import com.niiwoo.civet.user.dto.UserPersonalDubboInfoDTO;
import com.niiwoo.civet.user.dto.UserProfessionDubboInfoDTO;
import com.niiwoo.civet.user.dto.request.LoanUserAuditReportRequestDTO;
import com.niiwoo.civet.user.dto.response.*;
import com.niiwoo.civet.user.enums.UserDataStatusEnum;
import com.niiwoo.civet.user.enums.UserDataTypeEnum;
import com.niiwoo.civet.user.enums.UserPersonalEnum;
import com.niiwoo.civet.user.service.*;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import com.niiwoo.tripod.base.utils.IdCardUtils;
import com.niiwoo.tripod.consumer.component.FileUploadHandler;
import com.niiwoo.tripod.face.auth.LinkFaceAuth;
import com.niiwoo.tripod.web.annotation.AuthIgnore;
import com.niiwoo.tripod.web.util.PrincipalContext;
import com.niiwoo.tripod.web.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.FastDateFormat;
import org.joda.time.LocalDate;
import org.joda.time.Months;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @Description: 标的信息
 * @Author:LiJian
 * @Date:2017/10/11
 */
@Slf4j
@RestController
@RequestMapping("/projectInfo")
@Api(tags = "标的信息(李健)", description = "/projectInfo")
public class ProjectInfoController {
    @Reference(version = "1.0.0")
    private UserDataDubboService userDataDubboService;
    @Reference(version = "1.0.0")
    private ProjectCommonDubboService projectCommonDubboService;
    @Reference(version = "1.0.0")
    private UserDataSnapshotDubboService userDataSnapshotDubboService;
    @Reference(version = "1.0.0")
    private UserIdentityDubboService userIdentityDubboService;
    @Reference(version = "1.0.0")
    private UserStatusDubboService userStatusDubboService;
    @Reference(version = "1.0.0")
    private TianchengDataDubboService tianchengDataDubboService;
    @Reference(version = "1.0.0")
    private TianChengDataAnalysisDubboService tianChengDataAnalysisDubboService;
    @Reference(version = "1.0.0")
    private ProjectDubboService projectDubboService;
    @Reference(version = "1.0.0")
    private TradeConfigDubboService tradeConfigDubboService;
    @Reference(version = "1.0.0")
    private PortraitAuthDubboService portraitAuthDubboService;
    @Reference(version = "1.0.0")
    private LoanUserDubboService loanUserDubboService;
    @Reference(version = "1.0.0")
    private YXCreditCardDubboService yxCreditCardDubboService;
    @Reference(version = "1.0.0")
    private UserCreditDubboService userCreditDubboService;

    @Autowired
    PrivacyMasks privacyMasks;

    FastDateFormat fastDateFormat = FastDateFormat.getInstance("yyyy-MM-dd");

    @Autowired
    LinkFaceAuth linkFaceAuth;

    @Autowired
    FileUploadHandler fileUploadHandler;
    @Reference(version = "1.0.0")
    private UserBasicInfoDubboService userBasicInfoDubboService;
    @Reference(version = "1.0.0")
    private UserAuthorizationInfoDubboService userAuthorizationInfoDubboService;
    @Reference(version = "1.0.0")
    private UserImageFileDubboService userImageFileDubboService;
    @Reference(version = "1.0.0")
    private OrgProjectDubboService orgProjectDubboService;

    @Reference(version = "1.0.0")
    private OrgProjectOrderDubboService orgProjectOrderDubboService;


    @PostMapping("/loanUserDataInfo")
    @ApiOperation("借款人信息查询(吴科)")
    @AuthIgnore
    public Result<LoanUserDataInfoResponseVO> loanUserDataInfo(@RequestBody @Valid LoanUserDataInfoRequestVO requestVO) {
        String loginUserId = PrincipalContext.getUserId();
        String borrowUserId = requestVO.getBorrowUserId();
        Long projectId = requestVO.getProjectId();

        log.info("loanUserDataInfo.borrowUserId={},projectId={},start",borrowUserId,projectId);

        ProjectDTO projectDTO = projectDubboService.selectProjectById(projectId);
        Byte projectType = projectDTO.getType(); //标的类型获取
        Optional<UserInfoSnapshotRespDTO> userInfoSnapshotRespDTOOpt = Optional.ofNullable(userDataSnapshotDubboService.userInfoSnapshotQuery(borrowUserId,projectId));

        /*LoanUserDataInfoResponseVO vo = this.loanUserDataSnapshotQuery(loginUserId,borrowUserId,projectId);
        log.info("loanUserDataInfo.loanUserDataSnapshotQuery.borrowUserId={},projectId={},vo={}",borrowUserId,projectId,vo);
        if(vo==null) {
            vo = this.loanUserDataNewestQuery(loginUserId,borrowUserId);
            log.info("loanUserDataInfo.loanUserDataNewestQuery.borrowUserId={},projectId={},vo={}",borrowUserId,projectId,vo);
        }*/
        LoanUserDataInfoResponseVO vo = new LoanUserDataInfoResponseVO();
        if (projectType.equals(ProjectTypeEnum.ORG_SPEEDLOAN_NEW.getValue()) ||
                projectType.equals(ProjectTypeEnum.DECORATION_LOAN.getValue())) {
            //极速借（机构）信息活动
            vo = orgLoanInfo(projectId, projectDTO.getLoanType());
            UserBasicInfoResponseVO responseVO = vo.getUserBasicInfo();
            responseVO.setMobileNoAuthStatus((byte)0);
            vo.setUserBasicInfo(responseVO);
        }else{
            UserBasicInfoResponseVO userBasicInfoResponseVO = this.loanUserBasicInfo(borrowUserId, userInfoSnapshotRespDTOOpt);
            //查询缓存调用天秤考拉实名认证接口
            UserPortraitParamDTO portraitParamDTO = userIdentityDubboService.queryUserPortraitParam(requestVO.getBorrowUserId());
            MobileRealNameResponseDTO realNameResponse = userCreditDubboService.queryMobileRealNameForTiancheng(portraitParamDTO.getRealName(),
                    org.apache.commons.lang3.StringUtils.isBlank(portraitParamDTO.getIdentityCard()) ? null : privacyMasks.decryptPrivacy(portraitParamDTO.getIdentityCard()),
                    org.apache.commons.lang3.StringUtils.isBlank(portraitParamDTO.getMobilePhone()) ? null : privacyMasks.decryptPrivacy(portraitParamDTO.getMobilePhone()),requestVO.getBorrowUserId());
            userBasicInfoResponseVO.setMobileNoAuthStatus(Byte.valueOf(realNameResponse.getValidResultStatus()));
            vo.setUserBasicInfo(userBasicInfoResponseVO);
            vo.setUserPersonalInfo(this.loanUserPersonalInfo(loginUserId, borrowUserId, projectId, userInfoSnapshotRespDTOOpt));
            vo.setUserIdentityInfo(this.loanUserIdentityInfo(borrowUserId, userInfoSnapshotRespDTOOpt));
            vo.setUserProfessionInfo(this.loanUserProfessionInfo(borrowUserId, userInfoSnapshotRespDTOOpt));

            if (ProjectTypeEnum.ORG_SPEEDLOAN_NEW.getValue().equals(projectType)) {
                vo.setSocialSecurityInfo(getOrgProjectSocialSecurityInfo(projectId));
            } else {
                vo.setSocialSecurityInfo(this.loanUserSocialSecurityInfo(borrowUserId, projectId));
            }

            if (ProjectTypeEnum.CARD_NIU_LOAN.getValue().equals(projectType)) {
                this.cardNiuCreditCardInfo(borrowUserId, projectId, vo);
            } else if (ProjectTypeEnum.ORG_SPEEDLOAN_NEW.getValue().equals(projectType)) {
                vo.setCreditCardInfo(getOrgProjectCreditCardInfo(projectId));
            } else {
                this.setCreditCardInfo(borrowUserId, vo);
            }
            //判断是否是消费贷类型标的
            if (ProjectTypeEnum.CONSUME_LOAN.getValue().equals(projectType)){
                vo.setConsumeInfo(this.loanConsumeInfo(borrowUserId));
            }


        }
        // 相关数据打码 ***
        this.loanUserDataInfoMask(vo);
        log.info("loanUserDataInfo.borrowUserId={},projectId={},vo={} end",borrowUserId,projectId,JSON.toJSONString(vo));
        return Result.with(vo);
    }
    //获取消费信息
    private LoanConsumeInfoResponseVO loanConsumeInfo(String borrowUserId){
        LoanConsumeInfoResponseDTO responseDTO = userDataDubboService.selectLoanConsumeInfo(borrowUserId);
        LoanConsumeInfoResponseVO responseVO = new LoanConsumeInfoResponseVO();
        responseVO.setZhimaScore(responseDTO.getZhimaScore());
        responseVO.setTaoqiValue(responseDTO.getTaoqiValue());
        responseVO.setYearVolume(responseDTO.getYearVolume());
        return responseVO;
    }
    //极速借机构（个人标房产信息获取）
    private LoanUserDataInfoResponseVO orgLoanInfo(Long projectId, Byte loanType){
        LoanUserDataInfoResponseVO responseVO = new LoanUserDataInfoResponseVO();

        OrgApplyLoanInfoResponseDTO responseDTO = orgProjectDubboService.queryOrgApplyLoanInfo(projectId);
        if (responseDTO == null){
            return null;
        }
        OrgApplyPersonResponseDTO personResponseDTO = responseDTO.getOrgApplyPersonResponseDTO();
        OrgApplyWorkResponseDTO workResponseDTO = responseDTO.getOrgApplyWorkResponseDTO();
        OrgApplyHouseResponseDTO houseResponseDTO = responseDTO.getOrgApplyHouseResponseDTO();
        //个人信息
        if (personResponseDTO != null){
            UserBasicInfoResponseVO userBasicInfoResponseVO = new UserBasicInfoResponseVO();
            userBasicInfoResponseVO.setMobileNo(privacyMasks.decryptPrivacy(personResponseDTO.getBorrowerMobile()));
            userBasicInfoResponseVO.setUserId(personResponseDTO.getUserId());
            userBasicInfoResponseVO.setGender(personResponseDTO.getBorrowerGender()); //1、男 2、女
            responseVO.setUserBasicInfo(userBasicInfoResponseVO);
            UserPersonalResponseVO userPersonalInfo = new UserPersonalResponseVO();
            userPersonalInfo.setLivingAddress(personResponseDTO.getBorrowerAddress());
            byte edu = personResponseDTO.getEducation().byteValue() ;
            userPersonalInfo.setEducationLevel((byte)(edu+(byte) 1));
            Byte marriage = personResponseDTO.getMarriage();
            if (marriage.byteValue() != 3){
                byte marriageByte = (byte)(marriage.byteValue() + (byte)1);
                userPersonalInfo.setMaritalStatus(Byte.valueOf(marriageByte));
            }else {
                userPersonalInfo.setMaritalStatus(Byte.valueOf("0")); //其他
            }
            userPersonalInfo.setEducationAuthStatus(personResponseDTO.getEducation());
            userPersonalInfo.setEducationLevelDesc(UserPersonalEnum.UserEduLevelEnum.getByLevel(userPersonalInfo.getEducationLevel()).getDesc()); //教育水平描述
            userPersonalInfo.setMaritalStatusDesc(UserPersonalEnum.UserMaritalStatusEnum.getByLevel(userPersonalInfo.getMaritalStatus()).getDesc());//婚姻状况描述
            UserIdentityInfoResponseVO identityInfoResponseVO = new UserIdentityInfoResponseVO();
            String cardId = privacyMasks.decryptPrivacy(personResponseDTO.getBorrowerIdCard());
            identityInfoResponseVO.setAge(Optional.ofNullable(cardId).map(idCard->IdCardUtils.getAgeByIdCard(idCard)).orElse(0));
            identityInfoResponseVO.setSex(personResponseDTO.getBorrowerGender());

            // 籍贯
            if (StringUtils.isEmpty(personResponseDTO.getNativePlace())) {
                identityInfoResponseVO.setPlaceOfOrigin(getPlaceOfOrigin(cardId));
            } else {
                identityInfoResponseVO.setPlaceOfOrigin(personResponseDTO.getNativePlace());
            }

            identityInfoResponseVO.setName(personResponseDTO.getBorrowerName());
            identityInfoResponseVO.setIdCard(cardId);
            identityInfoResponseVO.setNameAuthStatus(Byte.valueOf("1")); //实名认证状态：1已认证
            identityInfoResponseVO.setNameAuthStatusDesc("通过实名认证");
            responseVO.setUserIdentityInfo(identityInfoResponseVO);
            responseVO.setUserPersonalInfo(userPersonalInfo);
        }
        //工作信息
        if (workResponseDTO != null){
            UserProfessionResponseVO professionResponseVO = new UserProfessionResponseVO();
            professionResponseVO.setCompanyName(workResponseDTO.getCompanyName());
            professionResponseVO.setCompanyAddress(workResponseDTO.getCompanyAddress());
            professionResponseVO.setCompanyPhone(workResponseDTO.getCompanyPhone());
            professionResponseVO.setDepartment(workResponseDTO.getDepartment());
            professionResponseVO.setPosition(workResponseDTO.getJob());
            responseVO.setUserProfessionInfo(professionResponseVO);

            // 生意贷工作信息
            WorkInformationResponseVO workInformation = new WorkInformationResponseVO();
            workInformation.setCompanyName(org.apache.commons.lang3.StringUtils.isBlank(workResponseDTO.getCompanyName()) ? null : workResponseDTO.getCompanyName());
            workInformation.setRepresentative(org.apache.commons.lang3.StringUtils.isBlank(workResponseDTO.getCorporateRepresentative()) ? null : workResponseDTO.getCorporateRepresentative());
            workInformation.setManagementAddress(org.apache.commons.lang3.StringUtils.isBlank(workResponseDTO.getCompanyAddress()) ? null : workResponseDTO.getCompanyAddress());
            workInformation.setShareProportion((workResponseDTO.getStockShareRatio() != null && workResponseDTO.getStockShareRatio().compareTo(new BigDecimal("0")) !=0) ? workResponseDTO.getStockShareRatio().multiply(new BigDecimal("100")).stripTrailingZeros().toPlainString() + "%" : null);
            workInformation.setRegistrationTime(org.apache.commons.lang3.StringUtils.isBlank(workResponseDTO.getRegistrationTime()) ? null : workResponseDTO.getRegistrationTime());
            workInformation.setManagementYears((workResponseDTO.getOperationYears() != null && workResponseDTO.getOperationYears() != 0) ? workResponseDTO.getOperationYears() + "年" : null);
            workInformation.setCompanyPhone(workResponseDTO.getCompanyPhone());
            responseVO.setWorkInfo(workInformation);
        }

        boolean isBusinessLoan = loanType != null && LoanTypeEnum.BUSINESS_LOAN.equals(LoanTypeEnum.enumOf(loanType));
        //房产信息
        // 生意贷不需要展示房产信息
        if(houseResponseDTO != null && !isBusinessLoan){
            UserHouseInfoResponseVO houseInfoResponseVO = new UserHouseInfoResponseVO();
            BeanUtils.copyProperties(houseResponseDTO,houseInfoResponseVO);
            if(houseInfoResponseVO.getHouseArea() != null){
                houseInfoResponseVO.setHouseArea(houseInfoResponseVO.getHouseArea()+ "平方米");
            }
            if (houseInfoResponseVO.getHouseYears() != null){
                houseInfoResponseVO.setHouseYears(houseInfoResponseVO.getHouseYears()+"年");
            }
            responseVO.setUserHouseInfo(houseInfoResponseVO);
        }
        //联系人信息
        // 借款人联系人关系0，父亲 1，母亲 2，兄弟 3，姐妹 4，子女 5，同事 6，朋友 7，其他 8，配偶
        // 联系人关系：1配偶、2父亲、3母亲、4兄弟、5姐妹、6子女、7其他、8同事、9朋友;
        if(responseDTO.getOrgApplyPersonResponseDTO().getLinkManInfoDTOList() != null){
            List<LinkManInfoVO> linkManInfoVOList = new ArrayList<>();
            responseDTO.getOrgApplyPersonResponseDTO().getLinkManInfoDTOList().forEach(link ->{
                LinkManInfoVO linkManInfoVO = new LinkManInfoVO();
                linkManInfoVO.setMobileNo(this.maskMobile(link.getMobileNo()));
                linkManInfoVO.setOrderNo(link.getOrderNo());
                linkManInfoVO.setRelation(link.getRelation());
                linkManInfoVO.setName(this.maskName(link.getName()));
                linkManInfoVOList.add(linkManInfoVO);
            });
            responseVO.getUserPersonalInfo().setLinkManInfoList(linkManInfoVOList);
        }

        return responseVO;
    }

    //获取借款人基本信息（你我标的获取）
    public UserBasicInfoResponseVO loanUserBasicInfo(String borrowUserId,Optional<UserInfoSnapshotRespDTO> userInfoSnapshotRespDTOOpt){
        UserBasicInfoResponseVO basicInfoResponseVO = new UserBasicInfoResponseVO();
        return userInfoSnapshotRespDTOOpt.map(userInfoSnapshotRespDTO->{
            BeanUtils.copyProperties(userInfoSnapshotRespDTO, basicInfoResponseVO);
            return basicInfoResponseVO;
        }).orElseGet(()->{
            UserBasicInfoResponseDTO userBasicInfo = userBasicInfoDubboService.getUserBasicInfo(borrowUserId);
            if (userBasicInfo == null) {
                return null;
            }
            BeanUtils.copyProperties(userBasicInfo, basicInfoResponseVO);
            return basicInfoResponseVO;
        });
    }

    //获取借款人个人信息
    public UserPersonalResponseVO loanUserPersonalInfo(String loginUserId,String borrowUserId,Long projectId,Optional<UserInfoSnapshotRespDTO> userInfoSnapshotRespDTOOpt){
        UserPersonalResponseVO userPersonalResponseVO = new UserPersonalResponseVO();
        userInfoSnapshotRespDTOOpt.map(userInfoSnapshotRespDTO->{
            BeanUtils.copyProperties(userInfoSnapshotRespDTO, userPersonalResponseVO);
            return null;
        }).orElseGet(()->{
            UserPersonalDubboInfoDTO userPersonalDubboInfoDTO = userDataDubboService.userPersonalInfo(borrowUserId);
            if (userPersonalDubboInfoDTO == null) {
                return null;
            }
            BeanUtils.copyProperties(userPersonalDubboInfoDTO, userPersonalResponseVO);
            return null;
        });

        userPersonalResponseVO.setLinkManInfoList(this.loanUserLinkManInfoList(loginUserId,borrowUserId,projectId));
        userPersonalResponseVO.setLivingAddress(userPersonalResponseVO.getLivingProvince()+userPersonalResponseVO.getLivingCity()+userPersonalResponseVO.getLivingArea()+userPersonalResponseVO.getLivingAddress());
        return userPersonalResponseVO;
    }

    //获取借款人联系人信息
    public List<LinkManInfoVO> loanUserLinkManInfoList(String loginUserId,String borrowUserId,Long projectId){
        Optional<List<LinkmanInfoSnapshotRespDTO>> linkmanInfoSnapshotRespDTOListOpt = Optional.ofNullable(userDataSnapshotDubboService.linkmanInfoSnapshotQuery(projectId));
        return linkmanInfoSnapshotRespDTOListOpt.map(linkmanInfoSnapshotList->{
            List<LinkManInfoVO> linkManInfoList = new ArrayList<>();
            for(LinkmanInfoSnapshotRespDTO linkmanInfoSnapshot :linkmanInfoSnapshotList){
                LinkManInfoVO linkManInfoVO = new LinkManInfoVO();
                BeanUtils.copyProperties(linkmanInfoSnapshot, linkManInfoVO);
                linkManInfoVO.setMobileNo(this.maskMobile(linkManInfoVO.getMobileNo()));
                linkManInfoVO.setName(this.maskName(linkManInfoVO.getName()));
                linkManInfoList.add(linkManInfoVO);
                if(linkManInfoList.size() >= 2){
                    break;
                }
            }
            return linkManInfoList;
        }).orElseGet(()->{
            UserPersonalDubboInfoDTO userPersonalDubboInfoDTO = userDataDubboService.userPersonalInfo(borrowUserId);
            if (userPersonalDubboInfoDTO == null) {
                return null;
            }
            List<LinkManDubboInfoDTO> linkManDubboInfoDTOList = userPersonalDubboInfoDTO.getLinkManInfoList();
            if (!CollectionUtils.isEmpty(linkManDubboInfoDTOList)) {
                List<LinkManInfoVO> linkManInfoList = new ArrayList<>();
                for(LinkManDubboInfoDTO linkManDubboInfoDTO :linkManDubboInfoDTOList){
                    LinkManInfoVO linkManInfoVO = new LinkManInfoVO();
                    BeanUtils.copyProperties(linkManDubboInfoDTO, linkManInfoVO);
                    linkManInfoVO.setName(this.maskName(linkManInfoVO.getName()));
                    linkManInfoVO.setMobileNo(this.maskMobile(linkManInfoVO.getMobileNo()));
                    linkManInfoList.add(linkManInfoVO);
                    if(linkManInfoList.size() >= 2){
                        break;
                    }
                }
                return linkManInfoList;
            }
            return null;
        });
    }

    //获取借款人个人信息
    public UserIdentityInfoResponseVO loanUserIdentityInfo(String borrowUserId,Optional<UserInfoSnapshotRespDTO> userInfoSnapshotRespDTOOpt){
        UserIdentityInfoResponseVO userIdentityInfoVO = new UserIdentityInfoResponseVO();
        return userInfoSnapshotRespDTOOpt.map(userInfoSnapshot->{
            BeanUtils.copyProperties(userInfoSnapshot, userIdentityInfoVO);
            DataStatusResponseDTO nameAuthStatusDTO = userStatusDubboService.getByUserIdAndType(borrowUserId, UserDataTypeEnum.TWO_ELEMENT);
            Byte nameAuthStatus = (nameAuthStatusDTO == null ? UserDataStatusEnum.RealNameAuthStatus.NOT_CERTIFIED.getStatus() : nameAuthStatusDTO.getDataStatus());
            userIdentityInfoVO.setNameAuthStatus(nameAuthStatus);
            userIdentityInfoVO.setNameAuthStatusDesc(UserDataStatusEnum.RealNameAuthStatus.of(nameAuthStatus).getDesc());
            userIdentityInfoVO.setAge(Optional.ofNullable(userIdentityInfoVO.getIdCard()).map(idCard->IdCardUtils.getAgeByIdCard(idCard)).orElse(0)); //根据身份证号获取年龄
            userIdentityInfoVO.setPlaceOfOrigin(this.getPlaceOfOrigin(userIdentityInfoVO.getIdCard()));
            return userIdentityInfoVO;
        }).orElseGet(()->{
            UserIdentityInfoResponseDTO userIdentityInfoResponseDTO = userIdentityDubboService.get(borrowUserId);
            if (userIdentityInfoResponseDTO != null) {
                BeanUtils.copyProperties(userIdentityInfoResponseDTO, userIdentityInfoVO);
                DataStatusResponseDTO nameAuthStatusDTO = userStatusDubboService.getByUserIdAndType(borrowUserId, UserDataTypeEnum.TWO_ELEMENT);
                Byte nameAuthStatus = (nameAuthStatusDTO == null ? UserDataStatusEnum.RealNameAuthStatus.NOT_CERTIFIED.getStatus() : nameAuthStatusDTO.getDataStatus());
                userIdentityInfoVO.setNameAuthStatus(nameAuthStatus);
                userIdentityInfoVO.setNameAuthStatusDesc(UserDataStatusEnum.RealNameAuthStatus.of(nameAuthStatus).getDesc());
                userIdentityInfoVO.setAge(Optional.ofNullable(userIdentityInfoVO.getIdCard()).map(idCard->IdCardUtils.getAgeByIdCard(idCard)).orElse(0)); //根据身份证号获取年龄
                userIdentityInfoVO.setPlaceOfOrigin(this.getPlaceOfOrigin(userIdentityInfoVO.getIdCard()));
            }
            return userIdentityInfoVO;
        });
    }

    //获取籍贯信息
    private String getPlaceOfOrigin(String identityCard){
        if(!StringUtils.hasText(identityCard)){
            return null;
        }
        String proCode = identityCard.substring(0,2)+"0000";
        String cityCode = identityCard.substring(0,4)+"00";

        String proName =  userDataDubboService.selectAreaNameByAreaCode(proCode);
        String cityName =  userDataDubboService.selectAreaNameByAreaCode(cityCode);
        proName = StringUtils.hasText(proName)?proName:"";
        cityName = StringUtils.hasText(cityName)?cityName:"";
        return proName+cityName;
    }

    //获取借款人职业信息
    public UserProfessionResponseVO loanUserProfessionInfo(String borrowUserId,Optional<UserInfoSnapshotRespDTO> userInfoSnapshotRespDTOOpt){
        UserProfessionResponseVO userProfessionResponseVO = new UserProfessionResponseVO();
        return userInfoSnapshotRespDTOOpt.map(userInfoSnapshotRespDTO->{
            BeanUtils.copyProperties(userInfoSnapshotRespDTO, userProfessionResponseVO);
            userProfessionResponseVO.setCompanyAddress(userProfessionResponseVO.getCompanyProvince()+userProfessionResponseVO.getCompanyCity()+userProfessionResponseVO.getCompanyArea()+userProfessionResponseVO.getCompanyAddress());
            return userProfessionResponseVO;
        }).orElseGet(()->{
            UserProfessionDubboInfoDTO userProfessionDubboInfoDTO = userDataDubboService.userProfessionInfo(borrowUserId);
            if (userProfessionDubboInfoDTO == null) {
                return null;
            }

            BeanUtils.copyProperties(userProfessionDubboInfoDTO, userProfessionResponseVO);
            userProfessionResponseVO.setCompanyAddress(userProfessionResponseVO.getCompanyProvince()+userProfessionResponseVO.getCompanyCity()+userProfessionResponseVO.getCompanyArea()+userProfessionResponseVO.getCompanyAddress());
            return userProfessionResponseVO;
        });
    }

    private SocialSecurityInfoResponseVO getOrgProjectSocialSecurityInfo(Long projectId) {
        SocialSecurityInfoResponseVO socialSecurityInfoResponseVO = new SocialSecurityInfoResponseVO();

        AssetOrgProjectResponseDTO orgProject = orgProjectDubboService.getAsserOrgProject(projectId);
        if (orgProject == null) {
            return socialSecurityInfoResponseVO;
        }

        OrgApplySocialSecurityInfoRespDTO socialSecurityInfoRespDTO = orgProjectOrderDubboService.queryOrderSocialSecurityInfo(orgProject.getOrderId());
        if (socialSecurityInfoRespDTO != null) {
            socialSecurityInfoResponseVO.setSocialAuthStatus(UserDataStatusEnum.SocialSecurityStatus.GETSUCCESS.getStatus());
            socialSecurityInfoResponseVO.setSocialAuthStatusDesc(UserDataStatusEnum.SocialSecurityStatus.GETSUCCESS.getDesc());
            socialSecurityInfoResponseVO.setCurrentStatus(SocialSecurityFeeStatus.NORMAL.getStatus());
            socialSecurityInfoResponseVO.setCurrentStatusDesc(SocialSecurityFeeStatus.NORMAL.getDesc());

            socialSecurityInfoResponseVO.setCompanyName(socialSecurityInfoRespDTO.getCompanyName());
            socialSecurityInfoResponseVO.setCity(socialSecurityInfoRespDTO.getCity());
            socialSecurityInfoResponseVO.setBaseNumber(socialSecurityInfoRespDTO.getBaseNumber());
            socialSecurityInfoResponseVO.setMonthCount(socialSecurityInfoRespDTO.getMonthCount());
        }

        return socialSecurityInfoResponseVO;
    }

    //获取借款人社保信息 （跟天秤保持一致取实时数据）
    public SocialSecurityInfoResponseVO loanUserSocialSecurityInfo(String borrowUserId,Long projectId){
        SocialSecurityInfoResponseVO socialSecurityInfoResponseVO = new SocialSecurityInfoResponseVO();

        SocialSecurityInfoRespDTO socialSecurityInfoRespDTO = userDataSnapshotDubboService.socialSecurityInfoQuery(borrowUserId);
        log.info("loanUserSocialSecurityInfo.userId={},projectId={},socialSecurityInfoRespDTO={}",borrowUserId,projectId,JSON.toJSONString(socialSecurityInfoRespDTO));
        if (socialSecurityInfoRespDTO == null) {
            return null;
        }
        BeanUtils.copyProperties(socialSecurityInfoRespDTO, socialSecurityInfoResponseVO);
        DataStatusResponseDTO socialAuthStatusDTO = userStatusDubboService.getByUserIdAndType(borrowUserId, UserDataTypeEnum.SOCIAL_SECURITY_OPERATOR_AUTHORIZE);
        Byte socialAuthStatus = (socialAuthStatusDTO == null ? UserDataStatusEnum.SocialSecurityStatus.NOCREDIT.getStatus() : socialAuthStatusDTO.getDataStatus());
        socialSecurityInfoResponseVO.setSocialAuthStatus(socialAuthStatus);
        socialSecurityInfoResponseVO.setCurrentStatus(SocialSecurityFeeStatus.NORMAL.getStatus());
        socialSecurityInfoResponseVO.setSocialAuthStatusDesc(UserDataStatusEnum.SocialSecurityStatus.getByStatus(socialAuthStatus).getDesc());
        socialSecurityInfoResponseVO.setCurrentStatusDesc(this.getSocialSecurityCurrentStatusDesc(socialSecurityInfoResponseVO.getCurrentStatus()));

        UserPortraitParamDTO portraitParamDTO = userIdentityDubboService.queryUserPortraitParam(borrowUserId);
        try {
            BorrowerInfoResponseDTO borrowerInfo = tianchengDataDubboService.postBorrowerInfo(
                    StringUtils.isEmpty(portraitParamDTO.getMobilePhone()) ? null : privacyMasks.decryptPrivacy(portraitParamDTO.getMobilePhone()), portraitParamDTO.getRealName(),
                    StringUtils.isEmpty(portraitParamDTO.getIdentityCard()) ? null : privacyMasks.decryptPrivacy(portraitParamDTO.getIdentityCard()), borrowUserId
            );
            log.info("借款人信息，查询天秤社保数据 borrowUserId={}, borrowerInfoResponseDTO={}", borrowUserId, JSON.toJSONString(borrowerInfo));
            if(borrowerInfo != null && !StringUtils.isEmpty(borrowerInfo.getSocialSecurityConsMonth())){
                socialSecurityInfoResponseVO.setMonthCount(Integer.parseInt(borrowerInfo.getSocialSecurityConsMonth()));
            }else {
                //socialSecurityInfoResponseVO.setMonthCount(Optional.ofNullable(userDataSnapshotDubboService.selectSocialSecurityMonthlyPaymentCount(borrowUserId)).orElse(Integer.valueOf("0")));
            }
        } catch (Exception e) {
            log.error("借款人信息，查询天秤社保数据异常 borrowUserId={}", borrowUserId, e);
        }
        log.info("loanUserSocialSecurityInfo.userId={},projectId={}, monthCount={}",borrowUserId, projectId, socialSecurityInfoResponseVO.getMonthCount());
        return socialSecurityInfoResponseVO;

    }

    /**
     * 卡牛——信用卡信息
     * @param borrowUserId
     * @param projectId
     * @param vo
     */
    private void cardNiuCreditCardInfo(String borrowUserId, Long projectId, LoanUserDataInfoResponseVO vo) {
        try {
            CreditCardAnalyRespDTO creditCardAnalyRespDTO = tianChengDataAnalysisDubboService.cardNiuCreditCardInfo(borrowUserId, projectId);
            if (creditCardAnalyRespDTO == null)
                return;

            CreditCardInfoResponseVO creditCardInfo = new CreditCardInfoResponseVO();
            if (StringUtils.hasText(creditCardAnalyRespDTO.getUseTime())){
                int useTime = Integer.parseInt(creditCardAnalyRespDTO.getUseTime());
                useTime = useTime / 365;
                if (useTime >= 1){
                    creditCardInfo.setCreditHistoryDuration(useTime + "年以上");
                } else {
                    creditCardInfo.setCreditHistoryDuration("1年以下");
                }
            }

            if(creditCardAnalyRespDTO.getSupremeAmount()!=null){
                double supremeAmount = creditCardAnalyRespDTO.getSupremeAmount().doubleValue();
                int result = Double.valueOf(Math.floor((supremeAmount - 1d) / 10000d)).intValue();
                if (result >= 1){
                    creditCardInfo.setMaxCreditQuota(result + "0000元以上");
                }else{
                    creditCardInfo.setMaxCreditQuota("10000元及以下");
                }
            }
            vo.setCreditCardInfo(creditCardInfo);
        } catch (NumberFormatException e) {
            log.error("cardNiuCreditCardInfo异常，userId={}  projectId={}",borrowUserId, projectId);
        }

    }

    private CreditCardInfoResponseVO getOrgProjectCreditCardInfo(Long projectId) {
        CreditCardInfoResponseVO creditCardInfo = new CreditCardInfoResponseVO();

        AssetOrgProjectResponseDTO orgProject = orgProjectDubboService.getAsserOrgProject(projectId);
        if (orgProject == null) {
            return creditCardInfo;
        }

        OrgApplyCreditCardInfoRespDTO creditCardInfoRespDTO = orgProjectOrderDubboService.queryOrderCreditCardInfo(orgProject.getOrderId());
        if (creditCardInfoRespDTO != null) {
            int creditHistoryDuration = creditCardInfoRespDTO.getDayCount() == null ? 0 : creditCardInfoRespDTO.getDayCount();
            creditHistoryDuration = creditHistoryDuration / 365;
            if (creditHistoryDuration >= 1) {
                creditCardInfo.setCreditHistoryDuration(creditHistoryDuration + "年以上");
            } else {
                creditCardInfo.setCreditHistoryDuration("1年以下");
            }

            double maxCreditQuota = creditCardInfoRespDTO.getLimit() == null ? 0 : creditCardInfoRespDTO.getLimit().doubleValue();
            int result = Double.valueOf(Math.floor((maxCreditQuota - 1d) / 10000d)).intValue();
            if (result >= 1) {
                creditCardInfo.setMaxCreditQuota(result + "0000元以上");
            } else {
                creditCardInfo.setMaxCreditQuota("10000元及以下");
            }

            creditCardInfo.setBankName(creditCardInfoRespDTO.getBankName());
            creditCardInfo.setIsHistoricalRepaymentOverdue(Byte.valueOf("0").equals(creditCardInfoRespDTO.getHasOverdueRecord()) ? Byte.valueOf("0") : Byte.valueOf("1"));
        }

        return creditCardInfo;
    }

    private void setCreditCardInfo(String userId,LoanUserDataInfoResponseVO vo){ //yxCreditCardDubboService
        try {
            YXCreditUserInfoRespDTO yxCreditUserInfoRespDTO = yxCreditCardDubboService.queryYXCreditUserInfo(userId);
            if(yxCreditUserInfoRespDTO==null){
                return;
            }
            CreditCardInfoResponseVO creditCardInfo = new CreditCardInfoResponseVO();
            if(StringUtils.hasText(yxCreditUserInfoRespDTO.getCreditHistoryDuration())){
                int creditHistoryDuration = Integer.parseInt(yxCreditUserInfoRespDTO.getCreditHistoryDuration());
                creditHistoryDuration = creditHistoryDuration / 365;
                if (creditHistoryDuration >= 1){
                    creditCardInfo.setCreditHistoryDuration(creditHistoryDuration + "年以上");
                }else{
                    creditCardInfo.setCreditHistoryDuration("1年以下");
                }
            }

            if(yxCreditUserInfoRespDTO.getMaxCreditQuota()!=null){
                double maxCreditQuota = yxCreditUserInfoRespDTO.getMaxCreditQuota().doubleValue();
                int result = Double.valueOf(Math.floor((maxCreditQuota - 1d) / 10000d)).intValue();
                if (result >= 1){
                    creditCardInfo.setMaxCreditQuota(result + "0000元以上");
                }else{
                    creditCardInfo.setMaxCreditQuota("10000元及以下");
                }
            }
            //信用卡发卡行查询
            Long cardId = yxCreditUserInfoRespDTO.getCommonCreditCardId();
            if (cardId != null){
                YXCreditCardInfoRespDTO yxCreditCardInfoRespDTO = yxCreditCardDubboService.queryYXCreditCardInfo(cardId);
                if (yxCreditCardInfoRespDTO != null){
                    creditCardInfo.setBankName(yxCreditCardInfoRespDTO.getBankName()); //发卡行名称
                }
            }
            //是否有历史逾期记录
            Byte isSeriouslyOverdue = yxCreditUserInfoRespDTO.getIsSeriouslyOverdue() ;
            Byte isSlightlyOverdue = yxCreditUserInfoRespDTO.getIsSlightlyOverdue();
            if (isSeriouslyOverdue != null && isSlightlyOverdue != null){
                creditCardInfo.setIsHistoricalRepaymentOverdue(isSeriouslyOverdue);
            }else if (isSeriouslyOverdue != null && isSlightlyOverdue == null){
                creditCardInfo.setIsHistoricalRepaymentOverdue(isSeriouslyOverdue);
            }else if (isSeriouslyOverdue == null && isSlightlyOverdue != null){
                creditCardInfo.setIsHistoricalRepaymentOverdue(isSlightlyOverdue);
            }else {
                creditCardInfo.setIsHistoricalRepaymentOverdue(Byte.valueOf("0")); //无逾期记录
            }

            vo.setCreditCardInfo(creditCardInfo);
        } catch (NumberFormatException e) {
            log.error("setCreditCardInfo异常，userId={}",userId);
        }
    }

    //获取社保当前缴费状态描述
    private String getSocialSecurityCurrentStatusDesc(String currentStatus){
        /*return Optional.ofNullable(currentStatus).map(s->{
            SocialSecurityFeeStatus sEnum = SocialSecurityFeeStatus.enumOf(s);
            return (sEnum==null?SocialSecurityFeeStatus.STOP.getDesc():sEnum.getDesc());
        }).orElse(SocialSecurityFeeStatus.STOP.getDesc());*/
        return SocialSecurityFeeStatus.NORMAL.getDesc();
    }

    private int getSocialMonthCount(String beginDate,Date lastPayDate){
        int socialMonthCount = 0;
        if(!StringUtils.hasText(beginDate) || lastPayDate==null){
            return socialMonthCount;
        }
        try{
            socialMonthCount = Months.monthsBetween(new LocalDate(beginDate).toDateTimeAtStartOfDay(), new LocalDate(lastPayDate).toDateTimeAtStartOfDay()).getMonths();
        }catch (Exception e){
            log.error("getSocialMonthCount异常，beginDate={}, lastPayDate={}", beginDate, lastPayDate);
        }
        return socialMonthCount;
    }

    private void loanUserDataInfoMask(LoanUserDataInfoResponseVO loanUserDataInfoResponseVO){
        UserBasicInfoResponseVO userBasicInfo = loanUserDataInfoResponseVO.getUserBasicInfo();
        if(userBasicInfo!=null){
            userBasicInfo.setMobileNo(this.maskMobile(userBasicInfo.getMobileNo()));
        }

        UserIdentityInfoResponseVO userIdentityInfo = loanUserDataInfoResponseVO.getUserIdentityInfo();
        if(userIdentityInfo!=null){
            userIdentityInfo.setIdCard(this.maskIdCard(userIdentityInfo.getIdCard()));
            userIdentityInfo.setName(this.maskName(userIdentityInfo.getName()));
            userIdentityInfo.setAddress(this.maskPlace(userIdentityInfo.getAddress()));
        }
        UserPersonalResponseVO userPersonalInfo = loanUserDataInfoResponseVO.getUserPersonalInfo();
        if(userPersonalInfo!=null){
            if (userPersonalInfo.getLivingProvince() == null && userPersonalInfo.getLivingCity() == null){
                userPersonalInfo.setLivingAddress(this.maskPlace(userPersonalInfo.getLivingAddress()));
            }else {
                userPersonalInfo.setLivingAddress(userPersonalInfo.getLivingProvince() + userPersonalInfo.getLivingCity() + userPersonalInfo.getLivingArea() + "*****");
            }
            userPersonalInfo.setEmail("");
        }
        UserProfessionResponseVO userProfessionInfo = loanUserDataInfoResponseVO.getUserProfessionInfo();
        if(userProfessionInfo!=null){
            userProfessionInfo.setCompanyName(this.maskCompanyName(userProfessionInfo.getCompanyName()));
            userProfessionInfo.setCompanyPhone(this.maskCompanyPhone(userProfessionInfo.getCompanyPhone()));
            if (userProfessionInfo.getCompanyProvince() == null && userProfessionInfo.getCompanyCity() == null){
                userProfessionInfo.setCompanyAddress(this.maskPlace(userProfessionInfo.getCompanyAddress()));
            }else{
                userProfessionInfo.setCompanyAddress(userProfessionInfo.getCompanyProvince()+userProfessionInfo.getCompanyCity()+"*****");
            }
        }
        SocialSecurityInfoResponseVO socialSecurityInfo = loanUserDataInfoResponseVO.getSocialSecurityInfo();
        if(socialSecurityInfo!=null){
            socialSecurityInfo.setCompanyName(socialSecurityInfo.getCity()+this.maskCompanyName(socialSecurityInfo.getCompanyName()));
            socialSecurityInfo.setMobileNo("");
            socialSecurityInfo.setIdCard("");
        }
        WorkInformationResponseVO workInfo = loanUserDataInfoResponseVO.getWorkInfo();
        if(workInfo!=null){
            workInfo.setCompanyName(this.maskCompanyName(workInfo.getCompanyName()));
            workInfo.setCompanyPhone(this.maskCompanyPhone(workInfo.getCompanyPhone()));
            workInfo.setManagementAddress(this.maskPlace(workInfo.getManagementAddress()));
            workInfo.setRepresentative(this.maskName(workInfo.getRepresentative()));
        }
    }

    public String maskIdCard(String idCard) {
        //为空 或者是本人，则不需要打码
        if(!StringUtils.hasText(idCard)){
            return idCard;
        }
        return idCard.substring(0, 3) + "*************" + idCard.substring(idCard.length() - 2, idCard.length());
    }

    public String maskMobile(String mobile) {
        if(!StringUtils.hasText(mobile)){
            return null;
        }
        return mobile.substring(0, 3) + "********" + mobile.substring(mobile.length(), mobile.length());
    }

    public String maskName(String Name) {
        //为空 或者是本人，则不需要打码
        if(!StringUtils.hasText(Name)){
            return Name;
        }
        return Name.substring(0, 1) + "**";
    }

    public String maskCompanyName(String companyName) {
        if(!StringUtils.hasText(companyName) || companyName.length()==1){
            return companyName;
        }
        int len = companyName.length();
        int subIndex = (len==2?1:len-2);
        return "***"+companyName.substring(subIndex);
    }

    public String maskCompanyPhone(String companyPhone) {
        if(!StringUtils.hasText(companyPhone)){
            return companyPhone;
        }
        int length = companyPhone.length();
        String subPhone = length < 4 ? companyPhone : companyPhone.substring(0,4);
        return subPhone + "****";
    }

    //籍贯打码
    public String maskPlace(String place){
        if(!StringUtils.hasText(place)){
            return place;
        }
        int cityIndex = place.indexOf("市");
        return place.substring(0,cityIndex+1)+"*****";
    }

    @PostMapping("/loanUserAuditReport")
    @ApiOperation("个人标借款人审核报告查询(吴科)")
    @AuthIgnore
    public Result<LoanUserAuditReportResponseVO> loanUserAuditReport(@RequestBody @Valid LoanUserDataInfoRequestVO requestVO) {
        log.info("loanUserAuditReport start");
        String loginUserId = PrincipalContext.getUserId();
        String borrowUserId = requestVO.getBorrowUserId();
        Long projectId = requestVO.getProjectId();
        log.info("loanUserAuditReport.borrowUserId={},projectId={},vo={} end",borrowUserId,projectId);
        LoanUserAuditReportRequestDTO requestDTO = new LoanUserAuditReportRequestDTO();
        BeanUtils.copyProperties(requestVO,requestDTO);
        requestDTO.setLoginUserId(loginUserId);
        LoanUserAuditReportResponseDTO responseDTO = loanUserDubboService.loanUserAuditReport(requestDTO);
        LoanUserAuditReportResponseVO vo = JSON.parseObject(JSON.toJSONString(responseDTO),LoanUserAuditReportResponseVO.class);
        log.info("loanUserAuditReport.borrowUserId={},projectId={},vo={} end",borrowUserId,projectId,JSON.toJSONString(vo));
        List<String> imageUrlH5 = new ArrayList<>();
        if(!CollectionUtils.isEmpty(vo.getImgFileList())){
            for (ImgFileSnapshotResponseVO imgFileSnapshotResponseVO : vo.getImgFileList()) {
                imageUrlH5.add(imgFileSnapshotResponseVO.getImgUrl());
            }
        }
        if(!CollectionUtils.isEmpty(vo.getHouseFileList())){
            for (RelatedFileVO relatedFileVO : vo.getHouseFileList()) {
                imageUrlH5.add(relatedFileVO.getFileUrl());
            }
        }
        if(!CollectionUtils.isEmpty(vo.getRelationFileList())){
            for (RelatedFileVO relatedFileVO : vo.getRelationFileList()) {
                imageUrlH5.add(relatedFileVO.getFileUrl());
            }
        }
        if(!CollectionUtils.isEmpty(vo.getContractFileList())){
            for (RelatedFileVO relatedFileVO : vo.getContractFileList()) {
                imageUrlH5.add(relatedFileVO.getFileUrl());
            }
        }
        vo.setImageUrlH5(imageUrlH5);
        return Result.with(vo);
    }

    @PostMapping("/loanCompanyAuditReport")
    @ApiOperation("企业标审核报告查询(杨玉威)")
    @AuthIgnore
    public Result<LoanUserAuditReportResponseVO> loanCompanyAuditReport(@RequestBody @Valid LoanUserDataInfoRequestVO requestVO) {

        String loginUserId = PrincipalContext.getUserId();
        String borrowUserId = requestVO.getBorrowUserId();
        Long projectId = requestVO.getProjectId();
        log.info("loanUserAuditReport.borrowUserId={},projectId={},vo={} end",borrowUserId,projectId);
        LoanUserAuditReportRequestDTO requestDTO = new LoanUserAuditReportRequestDTO();
        BeanUtils.copyProperties(requestVO,requestDTO);
        requestDTO.setLoginUserId(loginUserId);
        LoanUserAuditReportResponseDTO responseDTO = loanUserDubboService.loanCompanyAuditReport(requestDTO);
        LoanUserAuditReportResponseVO vo = JSON.parseObject(JSON.toJSONString(responseDTO),LoanUserAuditReportResponseVO.class);
        log.info("loanCompanyAuditReport.borrowUserId={},projectId={},vo={} end",borrowUserId,projectId,JSON.toJSONString(vo));
        return Result.with(vo);
    }

    @AuthIgnore
    @ApiOperation("借款用户画像")
    @PostMapping("/postUserPortrait")
    public Result<UserPortraitResponseVo> postUserPortrait(@RequestBody @Valid UserPortraitRequsetVo requestVO) {
        log.info("进入借款用户画像接口：{}", JSON.toJSONString(requestVO));
        UserPortraitResponseVo responseVo = new UserPortraitResponseVo();

        //查询用户画像需要的参数
        UserPortraitParamDTO portraitParamDTO = userIdentityDubboService.queryUserPortraitParam(requestVO.getBorrowUserId());
        responseVo.setHeadImage(portraitParamDTO.getHeadImage());       //用户头像地址
        responseVo.setNickName(portraitParamDTO.getNickName());         //用户昵称
        try {
            log.info("---> 通过天秤查询借款人画像相关信息:{}", requestVO.getBorrowUserId());
            BorrowerInfoResponseDTO borrowerInfoResponseDTO = tianchengDataDubboService.postBorrowerInfo(
                    org.apache.commons.lang3.StringUtils.isEmpty(portraitParamDTO.getMobilePhone()) ? null : privacyMasks.decryptPrivacy(portraitParamDTO.getMobilePhone()),
                    portraitParamDTO.getRealName(),
                    org.apache.commons.lang3.StringUtils.isEmpty(portraitParamDTO.getIdentityCard()) ? null : privacyMasks.decryptPrivacy(portraitParamDTO.getIdentityCard()),
                    requestVO.getBorrowUserId()
            );

            //评估时间使用标的审核时间
            ProjectDTO projectDTO = projectDubboService.selectProjectById(requestVO.getProjectId());
            if (projectDTO.getAuditedTime()!=null){
                borrowerInfoResponseDTO.setAssessTime(fastDateFormat.format(projectDTO.getAuditedTime()));
            }


            if (projectDTO.equals(ProjectTypeEnum.ORG_SPEEDLOAN_NEW.getValue()) ||
                    projectDTO.equals(ProjectTypeEnum.DECORATION_LOAN.getValue())) {
                //极速借（机构）信息活动
                borrowerInfoResponseDTO.setValidResultStatus("0");
            }else{
                //调用天秤考拉实名认证接口
                MobileRealNameResponseDTO realNameResponse = userCreditDubboService.queryMobileRealNameForTiancheng(portraitParamDTO.getRealName(),
                        org.apache.commons.lang3.StringUtils.isBlank(portraitParamDTO.getIdentityCard()) ? null : privacyMasks.decryptPrivacy(portraitParamDTO.getIdentityCard()),
                        org.apache.commons.lang3.StringUtils.isBlank(portraitParamDTO.getMobilePhone()) ? null : privacyMasks.decryptPrivacy(portraitParamDTO.getMobilePhone()),requestVO.getBorrowUserId());

                borrowerInfoResponseDTO.setValidResultStatus(realNameResponse.getValidResultStatus());
            }

            //用户姓名打码
            borrowerInfoResponseDTO.setRealName(maskName(borrowerInfoResponseDTO.getRealName()));
            //防止信息泄露不给前端以下资料，后续如果需要需加密
            borrowerInfoResponseDTO.setMobilePhone("");
            borrowerInfoResponseDTO.setIdentityCard("");
            if (borrowerInfoResponseDTO != null) BeanUtils.copyProperties(borrowerInfoResponseDTO, responseVo.getBorrowUserPortraitData());
        } catch (BeansException e) {
            log.error("通过天秤查询借款人画像相关信息，出现异常！{}", requestVO.getBorrowUserId(), e);
        }

        boolean isOverDue = false;
        try {
            log.info("---> 查询极速借记录统计信息:{}", requestVO.getBorrowUserId());
            SpeedLoanRecordStatisticsDTO statisticsDTO = projectDubboService.querySpeedLoanRecordStatistics(requestVO.getBorrowUserId());
            isOverDue = statisticsDTO.getTotalOverDueNum() > 0;
            if (statisticsDTO != null) BeanUtils.copyProperties(statisticsDTO, responseVo.getNiiwooLoanRecordData());

        } catch (Exception e) {
            log.error("查询极速借记录统计信息，出现异常！{}", requestVO.getBorrowUserId(), e);
        }
        if(org.apache.commons.lang3.StringUtils.isBlank(responseVo.getBorrowUserPortraitData().getM6ApplyNum())){
            responseVo.getBorrowUserPortraitData().setM6ApplyNum("0");
        }
        responseVo.getBorrowUserPortraitData().setOverdue(isOverDue ? "1" : "0");
        return Result.with(responseVo);
    }

}
